import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../models/user_account_entity.dart';
import '../../../routes/app_routes.dart';
import '../../../services/api_service.dart';
import '../../../services/common_service.dart';

class BalanceRecordLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();
  final loadingTip = '加载中...';
  final noMoreTip = '没有更多了';

  var tabTitles = ['全部', '收入', '支出'].obs;
  var isLoading = true.obs;
  var bottomTips = ''.obs;
  var balanceList = <UserAccountBalanceData>[].obs;
  var userList = <UserAccountFundData>[].obs;
  late TabController tabController;
  late ScrollController scrollController;

  late String role;

  final pageSize = 20;
  int _page = 1;
  int _type = 0;

  @override
  void onInit() {
    super.onInit();

    role = commonService.getRole();

    tabController = TabController(length: tabTitles.length, vsync: this);
    tabController.addListener(() {
      if (tabController.index.toDouble() == tabController.animation?.value) {
        _type = tabController.index;
        _page = 1;
        balanceList.clear();
        userList.clear();
        isLoading.value = true;
        _getAccountInfo(_page, _type);
      }
    });

    scrollController = ScrollController();
    scrollController.addListener(() {
      if (scrollController.position.pixels ==
          scrollController.position.maxScrollExtent) {
        bottomTips.value = loadingTip;
        _getAccountInfo(_page, _type);
      }
    });

    _getAccountInfo(_page, _type);
  }

  void _getAccountInfo(int page, int type) {
    var action = role == 'me' ? 'flowList' : 'balanceList';
    var source = role == 'me' ? '' : 'app';
    apiService
        .getBalanceInfo(page, pageSize, action, role, type, source)
        .then((account) => {
              isLoading.value = false,
              _page++,
              if (account != null)
                {
                  balanceList.addAll(account.balance?.data ?? []),
                  userList.addAll(account.balance?.allocData ?? []),
                  if (account.balance?.data?.length != pageSize)
                    {bottomTips.value = noMoreTip}
                }
              else
                {bottomTips.value = noMoreTip}
            });
  }

  // 点击记录
  void onClickRecord(int index) {
    Get.toNamed(RouteGet.balanceRecordDetail, arguments: balanceList[index]);
  }

  @override
  void onClose() {
    tabController.dispose();
    scrollController.dispose();
    super.onClose();
  }
}
